package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"xiwen/appconfig"
)

type Xiwen struct {
	gorm.Model
	Name    string `gorm:"type:varchar(20);not null" json:"name"`
	Age     string `gorm:"type:varchar(20);not null" json:"age"`
	Address string `gorm:"type:varchar(20);not null" json:"address"`
}

var DB *gorm.DB

func Init() {
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	var err error
	MysqlConfig := appconfig.Appon.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", MysqlConfig.User, MysqlConfig.Password, MysqlConfig.Host, MysqlConfig.Port, MysqlConfig.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	DB.AutoMigrate(&Xiwen{})
}
func (x *Xiwen) Add() error {
	return DB.Create(&x).Error
}
func (x *Xiwen) Update() error {
	return DB.Updates(&x).Error
}
func (x *Xiwen) Del() error {
	return DB.Delete(&x).Error
}
func (x *Xiwen) List() (n []*Xiwen, err error) {
	err = DB.Find(&n).Error
	return n, err
}
